package com.yilin.medical.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.ContentValues;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.widget.EditText;

/**
 * Created by admin on 14-10-29.
 */
public class SmsContent extends ContentObserver {

    private Cursor cursor = null;
    private Activity activity;
    private EditText editText;
    public SmsContent(Activity activity, EditText editText, Handler handler) {
        super(handler);
        this.activity = activity;
        this.editText = editText;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        cursor = activity.getContentResolver().query(Uri.parse("content://sms/inbox"),
                new String[]{"_id","address","read","body"},
                " body like ? and body like ? and  read=?",
                new String[]{"%扎根网%","%验证码%","0"},"_id desc");

        if(cursor != null && cursor.getCount()>0) {
            ContentValues values = new ContentValues();
            values.put("read","1");
            cursor.moveToNext();
            int smsBodyColunm = cursor.getColumnIndex("body");
            String body = cursor.getString(smsBodyColunm);
            JxLogUtil.i("gmx  body=" + body);
            editText.setText(getDynamicPassword(body));
        }

        JxLogUtil.i("gmx VERSION=" + Build.VERSION.SDK_INT);
        if(Build.VERSION.SDK_INT < 14) {
            cursor.close();
        }
    }


    private String getDynamicPassword(String str){
        Pattern pattern = Pattern.compile("(?<![0-9])([0-9]{6})(?![0-9])");
        Matcher m = pattern.matcher(str);
        String dynamicPassword = "";
        while (m.find()){
            dynamicPassword += m.group();
        }
        return dynamicPassword;
    }


}
